<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科室名称" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入科室名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['his:department:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['his:department:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['his:department:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 科室表格 -->
    <el-table v-loading="loading" :data="departmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="科室号" align="center" prop="id" />
      <el-table-column label="科室名称" align="center" prop="deptName" />
      <el-table-column label="负责人" align="center" prop="leader" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="关联医生" align="center" width="220">
        <template slot-scope="scope">
          <div v-if="scope.row.doctorList && scope.row.doctorList.length">
            <el-tooltip
              effect="light"
              placement="top"
              :content="scope.row.doctorList.map(d => d.doctorName).join('，')">
              <div class="doctor-tags">
                <el-tag
                  v-for="(doctor, index) in scope.row.doctorList.slice(0,2)"
                  :key="doctor.id"
                  size="mini"
                  type="info"
                  class="mr-5">
                  {{ doctor.doctorName }}
                </el-tag>
                <el-tag
                  v-if="scope.row.doctorList.length > 2"
                  size="mini"
                  type="info">
                  +{{ scope.row.doctorList.length - 2 }}
                </el-tag>
              </div>
            </el-tooltip>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['his:department:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['his:department:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改科室对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="680px"
      class="custom-dialog"
      append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="科室名称：" prop="deptName">
              <el-input
                v-model="form.deptName"
                placeholder="请输入科室名称"
                class="input-with-icon"
                prefix-icon="el-icon-office-building"
              />
            </el-form-item>

            <el-form-item label="科室号：" prop="parentId">
              <el-input
                v-model="form.parentId"
                placeholder="请输入科室号"
                class="input-with-icon"
                prefix-icon="el-icon-connection"
              />
            </el-form-item>

<!--            <el-form-item label="显示顺序：" prop="deptSort">-->
<!--              <el-input-number-->
<!--                v-model="form.deptSort"-->
<!--                :min="1"-->
<!--                :max="999"-->
<!--                controls-position="right"-->
<!--                class="full-width"-->
<!--              />-->
<!--            </el-form-item>-->

            <el-form-item label="状态：" prop="status">
              <el-select
                v-model="form.status"
                class="full-width"
                placeholder="请选择"
              >
                <el-option
                  label="正常"
                  value="0"
                  class="status-option"
                >
                  <span style="float: left">正常</span>
                  <span style="float: right; color: #67C23A;">
                <i class="el-icon-success"/>
              </span>
                </el-option>
                <el-option
                  label="停用"
                  value="1"
                  class="status-option"
                >
                  <span style="float: left">停用</span>
                  <span style="float: right; color: #F56C6C;">
                <i class="el-icon-error"/>
              </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 右列 -->
          <el-col :span="12">
            <el-form-item label="负责人：" prop="leader">
              <el-input
                v-model="form.leader"
                placeholder="请输入负责人"
                class="input-with-icon"
                prefix-icon="el-icon-user"
              />
            </el-form-item>

            <el-form-item label="联系电话：" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
                class="input-with-icon"
                prefix-icon="el-icon-mobile-phone"
              />
            </el-form-item>

<!--            <el-form-item label="邮箱：" prop="email">-->
<!--              <el-input-->
<!--                v-model="form.email"-->
<!--                placeholder="请输入邮箱"-->
<!--                class="input-with-icon"-->
<!--                prefix-icon="el-icon-message"-->
<!--              />-->
<!--            </el-form-item>-->
          </el-col>
        </el-row>

        <!-- 医生分配 -->
        <el-divider content-position="left">
          <i class="el-icon-user-solid"/> 医生分配
        </el-divider>

        <el-form-item label="选择医生：" prop="doctorIds">
          <el-select
            v-model="form.doctorIds"
            multiple
            filterable
            remote
            :remote-method="searchDoctors"
            :loading="doctorLoading"
            placeholder="请输入医生姓名搜索"
            class="full-width"
          >
            <el-option
              v-for="doctor in availableDoctors"
              :key="doctor.id"
              :label="`${doctor.doctorName}（${doctor.specialty}）`"
              :value="doctor.id"
            >
              <div class="doctor-option">
                <span class="name">{{ doctor.doctorName }}</span>
                <span class="dept">{{ doctor.deptName }}</span>
                <span class="title">{{ doctor.title }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="已分配医生：">
          <div class="selected-doctors">
            <el-tag
              v-for="doctorId in form.doctorIds"
              :key="doctorId"
              closable
              type="info"
              effect="plain"
              @close="removeDoctor(doctorId)"
              class="doctor-tag"
            >
              <i class="el-icon-user"/> {{ getDoctorName(doctorId) || '未知医生' }}
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
<!--        <el-button @click="cancel" size="medium">取 消</el-button>-->
        <el-button
          type="primary"
          @click="submitForm"
          size="medium"
          icon="el-icon-check"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDepartment, getDepartment, addDepartment, updateDepartment, deleteDepartment } from "@/api/his/department";
import { listDoctor } from "@/api/his/doctor"; // 假设已有医生API

export default {
  name: "Department",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      departmentList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptName: null,
        status: null
      },
      form: {
        id: null,
        deptName: null,
        parentId: null,
        deptSort: null,
        leader: null,
        phone: null,
        email: null,
        status: "0",
        remark: null,
        doctorIds: [] // 存储选中的医生ID
      },
      rules: {
        deptName: [
          { required: true, message: "科室名称不能为空", trigger: "blur" }
        ]
      },
      doctorLoading: false,
      filteredDoctors: [], // 搜索到的医生列表
      allDoctors: [] // 缓存所有医生信息，用于显示名称
    };
  },
  computed: {
    availableDoctors() {
      return this.filteredDoctors.filter(doctor =>
        !this.form.doctorIds.includes(doctor.id)
      );
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询科室列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listDepartment(this.queryParams);
        this.departmentList = await Promise.all(
          response.rows.map(async dept => {
            // 获取医生详细信息
            const res = await listDoctor({ deptId: dept.id });
            return { ...dept, doctorList: res.rows };
          })
        );
        this.total = response.total;
      } catch (error) {
        console.error(error);
      } finally {
        this.loading = false;
      }
    },
// 搜索按钮处理
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

// 重置查询条件
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置表单 */
    reset() {
      this.form = {
        id: null,
        deptName: null,
        parentId: null,
        deptSort: null,
        leader: null,
        phone: null,
        email: null,
        status: "0",
        remark: null,
        doctorIds: []
      };
      this.resetForm("form");
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增科室 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加科室";
    },

    /** 修改科室 */

    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getDepartment(id).then(response => {
        this.form = response.data;
        // 确保获取完整的医生信息
        this.form.doctorIds = response.data.doctorList.map(d => d.id);
        // 缓存医生信息用于显示名称
        this.allDoctors = response.data.doctorList;
        // 立即加载已关联医生
        this.open = true;
        this.title = "修改科室";
      });
    },

    /** 删除科室 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除科室编号为"' + ids + '"的数据项？').then(() => {
        return deleteDepartment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 搜索医生 */
// 修改后的搜索方法
    searchDoctors(query) {
      if (query) {
        this.doctorLoading = true;
        // 增加排除已选医生的参数
        listDoctor({
          doctorName: query,
          excludeIds: this.form.doctorIds.join(',') // 排除已选医生
        }).then(res => {
          this.filteredDoctors = res.rows;
          this.doctorLoading = false;
        });
      } else {
        this.filteredDoctors = [];
      }
    },

    /** 移除已选择的医生 */
    removeDoctor(doctorId) {
      this.form.doctorIds = this.form.doctorIds.filter(id => id !== doctorId);
    },

    /** 获取医生名称 */
    getDoctorName(doctorId) {
      const doctor = this.allDoctors.find(item => item.id === doctorId);
      return doctor ? doctor.doctorName : null;
    },

    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateDepartment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDepartment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
/* 自定义弹窗样式 */
.custom-dialog {
  border-radius: 8px;
}

.custom-dialog ::v-deep .el-dialog__header {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

.custom-dialog ::v-deep .el-dialog__title {
  font-size: 16px;
  color: #303133;
}

.input-with-icon ::v-deep .el-input__inner {
  padding-left: 35px;
}

.full-width {
  width: 100%;
}

.selected-doctors {
  min-height: 40px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
}

.doctor-tag {
  margin: 3px;
  padding: 0 10px;
  height: 28px;
  line-height: 26px;
}

.doctor-option {
  display: flex;
  justify-content: space-between;
  padding: 8px;
}
.doctor-option .name {
  width: 80px;
}
.doctor-option .dept {
  color: #909399;
  flex: 1;
  margin: 0 10px;
}
.doctor-option .title {
  color: #67C23A;
}

.status-option {
  padding: 0 10px;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}
/* 医生列表样式 */
.doctor-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.doctor-list {
  max-height: 300px;
  overflow-y: auto;
}

.doctor-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}

.doctor-item .name {
  margin-right: 10px;
}

.mr-5 {
  margin-right: 5px;
}
</style>
